<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';

function getCreative($database, $user) {
	$adgroupIdTempArray = [];
	$adgroupIdList = $database->query("SELECT bazaarId, adgroupId, adgroupName, campaignId, campaignName FROM cfg_adgroup where `companyId` = '{$user['companyId']}' AND `userId` = '{$user['userid']}'");
	if(is_array($adgroupIdList)){
		foreach ($adgroupIdList as $value) {
			array_push($adgroupIdTempArray, $value['adgroupId']);
		}
	}
	$creativeIdArray = [];
	$adgroupIdChunk = array_chunk($adgroupIdTempArray, 100);
	foreach ($adgroupIdChunk as $value) {
		$response = HttpPost('https://api.baidu.com/json/sms/service/CreativeService/getCreative', json_encode([
			'header'=>['username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token']],
			'body'=> [
        "creativeFields"=> [
					"creativeId",
					"adgroupId",
					"title",
					"status"
        ],
        "idType"=> 5,
        "ids"=> $value,
        "getTemp"=> 0
			]
		]));
		$bodyArray = json_decode($response, true);
		if(is_array($bodyArray['body']['data'])) {
			foreach ( $bodyArray['body']['data'] as $value ) {
				array_push($creativeIdArray, $value['creativeId']);
				$value['title'] = str_replace(',', '', $value['title']);
				$_array = getArray($adgroupIdList, $value['adgroupId'], 'adgroupId');
				$res = $database->query("select id from cfg_creative where `companyId` = '{$user['companyId']}' AND `creativeId` = '{$value['creativeId']}' LIMIT 1");
				if( isset($res[0]['id']) ) {
					$database->query( " UPDATE cfg_creative SET `customerid` = '{$user['customerid']}', `contact` = '{$user['contact']}', `status` = '{$value['status']}', `adgroupName` = '{$_array['adgroupName']}', `campaignName` = '{$_array['campaignName']}',
					  `title` = '{$value['title']}', `datatime` = NOW() WHERE id = '{$res[0]['id']}'; ");
				} else {
					$database->query("INSERT INTO cfg_creative ( `companyId`, `userType`, `userId`, `customerid`, `contact`, `bazaarId`, `adgroupName`, `campaignId`, `campaignName`, `creativeId`, `adgroupId`, `title`, `status`, `datatime`  ) values
					  ( '{$user['companyId']}', 1, '{$user['userid']}', '{$user['customerid']}', '{$user['contact']}', '{$user['bazaarId']}', '{$_array['adgroupName']}', '{$_array['campaignId']}', '{$_array['campaignName']}',
							  '{$value['creativeId']}', '{$value['adgroupId']}', '{$value['title']}', '{$value['status']}', NOW() ) " );
				}
			}
		}
	}
	if(count($creativeIdArray) > 0) {
		$creativeIdStr = implode(',', $creativeIdArray);
		$database->query(" DELETE FROM cfg_creative WHERE `companyId` = '{$user['companyId']}' AND `userType` = 1 AND `userId` = {$user['userid']} AND `creativeId` NOT IN ($creativeIdStr); " );
	}
}

run(function() use ($argv) {
	showMessage('获取创意数据.' );
	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}
  $userList = $database->query('SELECT `id`, `companyId`, `userid`, `customerid`, `contact`, `username`, `password`, `token`, `bazaarId` FROM cfg_expand where status = 1 and userType = 1');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'获取创意数据.' );
				getCreative($database, $user);
			});
		}
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');